package com.example.test;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;

/**
 * Created by Administrator on 2017/3/15.
 */

public class MyService extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    //创建的方法只会执行一次
    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this, "create", Toast.LENGTH_SHORT).show();
        //窃听电话
        TelephonyManager tm= (TelephonyManager) getSystemService(TELECOM_SERVICE);
        tm.listen(new MyTele(), PhoneStateListener.LISTEN_CALL_STATE);
    }

    class MyTele extends PhoneStateListener{
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            switch (state){
                case TelephonyManager.CALL_STATE_IDLE:
                    Toast.makeText(MyService.this, "空闲的", Toast.LENGTH_SHORT).show();
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    Toast.makeText(MyService.this, "响铃了", Toast.LENGTH_SHORT).show();
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    Toast.makeText(MyService.this, "摘机了", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    //启动的方法 调用一次就执行一次
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "start", Toast.LENGTH_SHORT).show();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, "销毁", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }
}
